import os
import sys
import re
import array
import config
import ragadef

Swaras = ragadef.RagaDef[config.Raga];
Suffix = [',','',"'"]
NoteIndex = {};
NoteRevIndex = {};
NumNotes = 0;
NumStates = 0;
MarkovMatrix = [];
CorpusCorpusFileList = [];

def CreateNoteIndex():
	global NoteIndex,Swaras,Suffix,MarkovOrder,NumStates,NumNotes
	for pitch in range(0,3,1):
		for i in range(0,len(Swaras),1):
			NoteIndex[Swaras[i]+Suffix[pitch]] = pitch*len(Swaras) + i;
			NoteRevIndex[pitch*len(Swaras) + i] = Swaras[i]+Suffix[pitch];
	NoteIndex['.'] = len(NoteIndex); NoteRevIndex[len(NoteRevIndex)] = '.';
#TODO::Decide whether END should be included in Notes
#	NoteIndex['END'] = len(NoteIndex);
	NumNotes = len(NoteIndex);
	NumStates = FindMarkovMatrixIndex([NumNotes-1]*config.MarkovOrder)+1;

def FindMarkovMatrixIndex(s):
	global NoteIndex;
	if(len(s)!=config.MarkovOrder):
		print "BAD PARAMATER::State has only %d notes. Need %d" %(len(s),config.MarkovOrder);
	temp = len(NoteIndex);
	index = 0;
	for i in range(0,config.MarkovOrder,1):
		index += s[i]*(temp**(config.MarkovOrder-i-1));
	return index;	

def InitMarkovMatrix():
	global MarkovMatrix,NumNotes,NumStates;
	for i in range(0,NumStates,1):
		MarkovMatrix.append(array.array('I',[0]*NumNotes));

#TODO::Improve this function to filter files
def GetCorpusCorpusFileList():
	global CorpusFileList;
	CorpusFileList = os.listdir(config.Path);

def isNonZero(x):
	return (x != 0);
def PrintMarkovMatrix():
	global MarkovMatrix,NoteIndex;
	for i in NoteIndex.keys():
		for j in NoteIndex.keys():
			for k in NoteIndex.keys():
				State = [NoteIndex[i],NoteIndex[j],NoteIndex[k]];
				StateIndex = FindMarkovMatrixIndex(State);
				if(len(filter(isNonZero, MarkovMatrix[StateIndex]))==0):
					continue;
				print "%d:" %(StateIndex);
				for p in NoteIndex.keys():
					if(MarkovMatrix[StateIndex][NoteIndex[p]] > 0):
						print i, j, k, p, MarkovMatrix[StateIndex][NoteIndex[p]];
